import { ProColumns, ProTable } from '@ant-design/pro-table';
import { message, Modal } from 'antd';
import React, { PropsWithChildren } from 'react';
import { SearchWordsType } from '@/models/searchWords';
import { addSearchWords } from '@/services/searchWordsService';

interface CreateSearchProps {
  modalVisible: boolean;
  columns: ProColumns<SearchWordsType.SuggestWordsSearchVo>[];
  onSubmit: () => void;
  onCancel: () => void;
}

/***
 *添加节点
 * @param fields
 */
const handleAdd = async (fields: SearchWordsType.SearchWordsAddRequest) => {
  const hide = message.loading('正在添加');
  try {
    await addSearchWords({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试');
    return false;
  }
};

const AdminCreateSearch: React.FC<PropsWithChildren<CreateSearchProps>> = (
  props,
) => {
  const { modalVisible, columns, onSubmit, onCancel } = props;

  return (
    <Modal
      destroyOnClose
      title="新建"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<
        SearchWordsType.SuggestWordsSearchVo,
        SearchWordsType.SearchWordsAddRequest
      >
        onSubmit={async (value) => {
          const success = await handleAdd({
            ...value,
            searchCategory: value.searchCategory,
            userId: value?.userId,
          });
          if (success) {
            onSubmit?.();
          }
        }}
        rowKey="id"
        type="form"
        columns={columns}
      />
    </Modal>
  );
};

export default AdminCreateSearch;
